<?php
error_reporting(7);

$showqueries = 1;
$exp = 1;
$debug = 1;

class db_MySQL {
	var $server = "localhost";
	var $database = "";
	var $user = "root";
	var $password = "";

	var $id = 0;
	var $querycount = 0;
	var $result;
	var $record = array();
	var $rows;
	var $insertid;

	var $errno;
	var $error;

	var $querylog = array();

	var $version;
	var $use_sql_cache = 0;

	/**
         * 是否 cache 结果集, query_first, fetch_one_array 有效
         *
         * @var bool
         */
	var $use_cache = true;

	var $debugInfo = '';

	function geterrdesc() {
		$this->error = mysql_error($this->id);
		return $this->error;
	}

	function geterrno() {
		$this->errno = mysql_errno($this->id);
		return $this->errno;
	}

	function connect() {
		global $usepconnect;
		if ($usepconnect == 1) {
			if (!$this->id = mysql_pconnect($this->server, $this->user, $this->password)) {
				$this->halt("数据库链接失败");
			}
		} else {
			if (!$this->id = mysql_connect($this->server, $this->user, $this->password)) {
				$this->halt("数据库链接失败");
			}
		}
		$this->selectdb();

		/*
		$v = $this->query_first("SELECT VERSION() AS version");
		$this->version = trim($v['version']);

		if (substr($this->version, 0, 6) >= '4.0.1') {
		$this->use_sql_cache = 1;
		}
		*/

		return $this->id;
	}

	function selectdb() {
		if (!mysql_select_db($this->database, $this->id)) {
			$this->halt("数据库链接失败.");
		}
	}

	function query($query_string) {
		global $querytime, $showqueries, $debug, $exp;

		if ($showqueries == 1) {
			global $script_start_time;
			$pageendtime = microtime();
			$starttime = explode(" ", $script_start_time);
			$endtime = explode(" ", $pageendtime);

			$beforetime = $endtime[0] - $starttime[0] + $endtime[1] - $starttime[1];
		}

		/*
		if($this->use_sql_cache AND substr(trim(strtoupper($query_string)), 0, 6) == 'SELECT'){
		$query_string = "SELECT SQL_CACHE ".substr($query_string, 6, strlen($query_string));
		}
		*/
		/*
		if (intval($_GET['movieid']) == 36553) {
		$log = date("Y-m-d H:i:s") . ": $query_string\n";
		$log .= "_________\n";
		$fp = fopen("/var/tmp/mysql_query.log", "a+");
		fwrite($fp, $log);
		fclose($fp);
		}
		*/
		//$this->result = @mysql_query($query_string, $this->id);
		$this->result = mysql_db_query($this->database, $query_string, $this->id);

		if (!$this->result) {
			$this->halt("SQL 无效: " . $query_string);
		}
		$this->querycount++;

		if ($showqueries == 1) {
			$pageendtime = microtime();
			$starttime = explode(" ", $script_start_time);
			$endtime = explode(" ", $pageendtime);
			$aftertime = $endtime[0] - $starttime[0] + $endtime[1] - $starttime[1];
			$querytime += $aftertime - $beforetime;
		}

		if ($debug == 1) {
			if ($this->querycount == 1) {
				$this->debugInfo .= "
                             <style type=\"text/css\">
                             <!--
                             pre, td,tr,table, font {
                                     font-size: 9px;
                                     font-family: verdana, arial, helvetica ,宋体;
                                     text-align: left;
                             }
                             pre {
                             	padding: 0px;
                             	margin: 0px;
                             }
                             hr {
                              	color: #FFFFFF;
                             }

                             .others, .sql, .time {
                                     font-size: 9px;
                                     font-family: verdana, arial, helvetica ,宋体;
                                     text-align: left;
                                     background-color: #EFEFEF;

                                     border-bottom: 1px solid #CCCCCC;
                                     padding: 3px;
                             }
                             -->
                             </style>
                             ";
			}

			$this->debugInfo .= "<pre><div class=\"sql\">Query: $query_string</div></pre>";
			$this->debugInfo .= "<div class=\"time\">
	                              Before time: $beforetime |
	                              After time: $aftertime |
	                              Query time: " . ($aftertime - $beforetime) . "
                             </div>";

			$debug_backtrace = debug_backtrace();

			//echo _backtrace(1);




			if (substr(trim(strtoupper($query_string)), 0, 6) == 'SELECT') {
				$explain = mysql_query("EXPLAIN $query_string", $this->id);
				$this->debugInfo .= "<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"3\" bgcolor=\"#666666\">
                                 <tr bgcolor=\"#EEEEEE\">
                                   <td>table</td>
                                   <td>type</td>
                                   <td>possible_keys</td>
                                   <td>key</td>
                                   <td>key_len</td>
                                   <td>ref</td>
                                   <td>rows</td>
                                   <td>Extra</td>
                                 </tr>\n";
				while ($data = mysql_fetch_array($explain)) {
					$this->debugInfo .= "<tr bgcolor=\"#FFFFFF\">\n";

					for($i = 0;$i < 8;$i++) {
						$this->debugInfo .= "<td>$data[$i]</td>\n";
					}
					$this->debugInfo .= "</tr>\n";
				}
				$this->debugInfo .= "</table>";
			}
			$this->debugInfo .= "<hr size=1>";
		}
		
		echo "<meta http-equiv=content-type content=\"text/html; charset=UTF-8\">\n";
		echo $this->debugInfo;
		$this->debugInfo = '';

		return $this->result;
	}

	function fetch_array($queryid, $type = MYSQL_ASSOC) {
		$this->record = mysql_fetch_array($queryid, $type);
		if (empty($queryid)) {
			$this->halt("queryid 无效:" . $queryid);
		}
		return $this->record;
	}

	function fetch_row($queryid) {
		$this->record = mysql_fetch_row($queryid);
		if (empty($queryid)) {
			$this->halt("queryid 无效:" . $queryid);
		}
		return $this->record;
	}

	/**
         * 运行 SQL 并返回结果
         *
         * @access public
         * @return array
         */
	function fetch_one_array($query_string, $result_type = MYSQL_ASSOC, $use_cache = 1) {
		//$this->result = $this->query($query);
		//$this->record = $this->fetch_array($this->result, $result_type);
		$this->record = $this->query_first($query_string, $result_type, $use_cache);
		return $this->record;
	}

	/**
         * 运行 SQL 并返回结果
         *
         * @access public
         * @param string $query_string
         * @param integer $result_type
         * @see mysql_fetch_array()
         * @param bool $use_cache 是否使用 cache, 默认是使用
         * @return array |false
         */
	function query_first($query_string, $result_type = MYSQL_ASSOC, $use_cache = 1) {
		$set_cache = 0;
		if ($this->use_cache AND $use_cache) {
			$key = 'db_' . $query_string . "_" . $result_type;
			$cache = new SmartCache($key);
			$cache->lifetime = 60;
			$this->record=  $cache->read($key);
			if ($this->record) {
				return $this->record;
			} else {
				//
				$set_cache = 1;
			}
		}

		$this->result = $this->query($query_string);
		$this->record = $this->fetch_array($this->result, $result_type);

		if ($set_cache) {
			$cache->write($this->record);
		}
		return $this->record;
	}

	/**
        * 运行 SQL 并以数组的形式返回所有结果
        *
        * @access public
        * @param string $query_string
        * @param integer $result_type
        * @return array |false
        */
	function query_all($query_string, $result_type = MYSQL_ASSOC) {
		$this->result = $this->query($query_string);
		if($this->result){
			$records = array();
			while($record = $this->fetch_array($this->result, $result_type)){
				$records[] = $record;
			}

		}
		return $records;
	}

	function num_rows($result) {
		$this->rows = mysql_num_rows($result);

		if (empty($result)) {
			$this->halt("fail to get mysql_num_rows");
		}
		return $this->rows;
	}

	function free_result($query) {
		if (!mysql_free_result($query)) {
			$this->halt("fail to mysql_free_result");
		}
	}

	function insert_id() {
		$this->insertid = mysql_insert_id();
		if (!$this->insertid) {
			$this->halt("fail to get mysql_insert_id");
		}
		return $this->insertid;
	}

	function affected_rows() {
		$this->affected_rows = mysql_affected_rows($this->id);
		return $this->affected_rows;
	}

	function date_seek($result, $i) {
		if (mysql_date_seek($result, $i)) {
			return true;
		} else {
			return false;
		}
	}

	function close() {
		@mysql_close($this->id);
	}

	function halt($msg) {
		global $technicalemail, $debug;
		$message = "<html>\n<head>\n";
		$message .= "<meta http-equiv=content-type content=\"text/html; charset=UTF-8\">\n";
		$message .= "<STYLE TYPE=\"text/css\">\n";
		$message .= "<!--\n";
		$message .= "td,body {\n";
		$message .= "font-family : Verdana, Arial, Helvetica, sans-serif;font-size : 12px;\n";
		$message .= "}\n";
		$message .= "</STYLE>\n";
		$message .= "</head>\n";
		$message .= "<body leftmargin=\"10\" topmargin=\"10\" marginwidth=\"10\" marginheight=\"10\" bgcolor=\"#EEEEEE\" text=\"#000000\" link=\"#006699\" vlink=\"#5493B4\">\n";
                //$message .= $this->debugInfo;
		$message .= "请尝试刷新你的浏览器,如果仍然无法正常显示,请联系<a href=\"mailto:$technicalemail\">管理员</a>.";
		$message .= "<HR>";

		$message .= "<table border=1 cellpadding=4 cellspacing=0 bordercolor=#FFFFFF>
                                       <tr width=30%>
                                <td>数据库出错</td>

                                ";
		$message .= "<td><textarea cols=\"80\" rows=\"10\" wrap=\"OFF\">" . htmlspecialchars($msg) . "</textarea>
                                       </td></tr>\n";

		$message .= "<tr><td>mysql error description</td>";

		$message .= "<td>" . $this->geterrdesc() . "\n</td></tr>";
		$message .= "<tr><td>mysql error number</td>";

		$message .= "<td>" . $this->geterrno() . "\n</td></tr>";

		$message .= "<tr><td>Database</td>";
		$message .= "<td>" . $this->database . "\n</td></tr>";

		$message .= "<tr><td>Linkid</td>";
		$message .= "<td>" . $this->id . "\n</td></tr>";

		$message .= "<tr><td>Date</td>";
		$message .= "<td>" . date("Y-m-d @ H:i") . "\n</td></tr>";

		$message .= "<tr><td>Script</td>";
		$message .= "<td>" . getenv("REQUEST_URI") . "\n</td></tr>";

		$message .= "<tr><td>Referer</td>";
		$message .= "<td>" . getenv("HTTP_REFERER") . "\n</td></tr>";

		$message .= "</table>";

		$message .= "</body>\n</html>";

		/*$headers  = "MIME-Version: 1.0\r\n";
		$headers .= "Content-type: text/html; charset=gb2312\r\n";
		$headers .= "From: \r\n";

		@mail($technicalemail, $msg, $message,$headers);
		*/
		// if ($_SESSION[isadmin]==1) {
		echo $message;
		// }
		exit;
	}
}

?>